package com.example.onlinemarket.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinemarket.R;
import com.example.onlinemarket.adapter.RecyclerViewAdapter;
import com.example.onlinemarket.model.MobileOrderItem;
import com.example.onlinemarket.model.OrderInfo;
import com.example.onlinemarket.util.ActivityUtil;
import com.example.onlinemarket.util.DialogUtil;
import com.example.onlinemarket.util.JSONUtil;

import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.util.HttpUtil.addGoodToShoppingCart;
import static com.example.onlinemarket.util.HttpUtil.cancelRefund;
import static com.example.onlinemarket.util.HttpUtil.confirmOrder;
import static com.example.onlinemarket.util.HttpUtil.delOrder;
import static com.example.onlinemarket.util.HttpUtil.refundOrder;
import static com.example.onlinemarket.util.HttpUtil.signOrder;

public class OrderInfoActivity extends BaseActivity {

    private TextView shopNameTv;
    private RecyclerView recyclerView;
    private RecyclerViewAdapter<MobileOrderItem> adapter;
    private TextView addressTv;
    private TextView orderIdTv;
    private TextView orderStatusTv;
    private TextView orderTimeTv;
    private TextView noteTv;
    private TextView totalPriceTv;
    private Button refundBtn;
    private Button cancelRefundBtn;
    private Button delOrderBtn;
    private Button signOrderBtn;
    private Button finishOrderBtn;

    private OrderInfo info;
    private int status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.activity_order_info);
        //初始化组件
        initWidgets();
        //初始化数据
        initData();
        //为组件设置事件监听器
        setWidgetsListener();
        //关闭加载提示框
        dismissProgressDialog();
    }

    //初始化数据
    private void initData() {
        Intent intent = getIntent();
        status = Integer.parseInt(intent.getStringExtra("status"));
        String orderJson = intent.getStringExtra("order");
        info = JSONUtil.fromJson(orderJson, OrderInfo.class);
        shopNameTv.setText(info.order.getShopName());
        orderIdTv.setText(String.valueOf(info.order.getOrderId()));
        addressTv.setText(info.order.getAddress());
        String status = info.order.getStatus();
        String statusText = status.contains("-")?status.split("-")[1]:status;
        orderStatusTv.setText(statusText);
        orderTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).format(new Date(Long.parseLong(intent.getStringExtra("date")))));
        setRecyclerViewAdapter(info.orderItemList);
        String note = info.order.getNote();
        if(note==null||note.isEmpty())
            noteTv.setVisibility(View.GONE);
        else{
            String noteText = "备注："+info.order.getNote();
            noteTv.setText(noteText);
        }
        double totalPrice = 0;
        for(MobileOrderItem item:info.orderItemList){
            totalPrice += item.sellPrice*item.goodNum;
        }
        String totalPriceText = "总价：￥"+totalPrice;
        totalPriceTv.setText(totalPriceText);
    }

    //初始化组件
    private void initWidgets() {
        shopNameTv = findViewById(R.id.tv_order_info_shop_name);
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        addressTv = findViewById(R.id.tv_order_info_address);
        orderIdTv = findViewById(R.id.tv_order_info_order_id);
        orderTimeTv = findViewById(R.id.tv_order_info_order_time);
        orderStatusTv = findViewById(R.id.tv_order_info_order_status);
        noteTv = findViewById(R.id.tv_order_info_note);
        totalPriceTv = findViewById(R.id.tv_order_info_total_price);
        refundBtn = findViewById(R.id.btn_refund);
        cancelRefundBtn = findViewById(R.id.btn_cancel_refund);
        delOrderBtn = findViewById(R.id.btn_del_order);
        signOrderBtn = findViewById(R.id.btn_sign_order);
        finishOrderBtn = findViewById(R.id.btn_finish_order);
    }

    //为组件设置事件监听器
    private void setWidgetsListener(){
        shopNameTv.setOnClickListener(v -> new Thread(() -> ActivityUtil.goShop(OrderInfoActivity.this, info.order.getShopId())).start());
        switch (status){
            case OrderActivity.UNSENT_STATUS:
                setTitle("等待发货");
                enableRefundBtn();
                break;
            case OrderActivity.SENT_STATUS:
                setTitle("等待签收");
                enableRefundBtn();
                enableSignOrderBtn();
                break;
            case OrderActivity.SIGNED_STATUS:
                setTitle("已签收");
                enableFinishOrderBtn();
                enableRefundBtn();
                break;
            case OrderActivity.REFUNDING_STATUS:
                setTitle("正在请求退款");
                enableCancelRefundBtn();
                break;
            case OrderActivity.REFUND_STATUS:
                setTitle("已退款");
                enableDelOrderBtn();
                break;
            case OrderActivity.CONFIRM_STATUS:
                setTitle("订单已关闭");
                enableDelOrderBtn();
                break;
            default:
                break;
        }
    }

    private RecyclerViewAdapter<MobileOrderItem> getAdapter(List<MobileOrderItem> orderItemList){
        return new RecyclerViewAdapter<MobileOrderItem>(this, R.layout.order_info_item, orderItemList) {
            @Override
            public int getLayoutId(int viewType) { return R.layout.order_info_item; }
            @Override
            public void convert(ViewHolder holder, MobileOrderItem data, int position) {
                holder.setText(R.id.good_name, data.goodName);
                holder.setImage(R.id.good_img, data.imgPath);
                String goodNum = "x"+data.goodNum;
                holder.setText(R.id.good_num, goodNum);
                String goodPrice = "￥"+data.sellPrice;
                holder.setText(R.id.good_price, goodPrice);
                String totalPrice = "总价：￥"+(data.goodNum*data.sellPrice);
                holder.setText(R.id.total_price, totalPrice);
                holder.setOnClickListener(R.id.btn_good_item_add_shopping_cart, v -> addGoodToShoppingCart(data.goodId));
            }
        };
    }

    private void setRecyclerViewAdapter(List<MobileOrderItem> orderItemList){
        adapter = getAdapter(orderItemList);
        recyclerView.setAdapter(adapter);
    }

    private void enableRefundBtn(){
        refundBtn.setVisibility(View.VISIBLE);
        refundBtn.setOnClickListener(v -> {
            AlertDialog dialog = DialogUtil.getDialog(this, "订单退款", "确定要退款吗", (dialog1, which) -> {
                new Thread(() -> refundOrder(info.order.getOrderId())).start();
                dialog1.dismiss();
                Toast.makeText(OrderInfoActivity.this, "正在申请退款，请等待商家处理", Toast.LENGTH_SHORT).show();
                finishActivity(info.order.getOrderId());
            });
            dialog.show();
        });
    }

    private void enableCancelRefundBtn(){
        cancelRefundBtn.setVisibility(View.VISIBLE);
        cancelRefundBtn.setOnClickListener(v -> {
            AlertDialog dialog = DialogUtil.getDialog(this, "取消退款", "确定要取消退款吗", (dialog1, which) -> {
                new Thread(() -> cancelRefund(info.order.getOrderId())).start();
                dialog1.dismiss();
                Toast.makeText(OrderInfoActivity.this, "取消退款成功", Toast.LENGTH_SHORT).show();
                finishActivity(info.order.getOrderId());
            });
            dialog.show();
        });
    }

    private void enableSignOrderBtn(){
        signOrderBtn.setVisibility(View.VISIBLE);
        signOrderBtn.setOnClickListener(v -> {
            AlertDialog dialog = DialogUtil.getDialog(this, "订单签收", "确定要签收吗", (dialog1, which) -> {
                new Thread(() -> signOrder(info.order.getOrderId())).start();
                dialog1.dismiss();
                Toast.makeText(OrderInfoActivity.this, "签收成功", Toast.LENGTH_SHORT).show();
                finishActivity(info.order.getOrderId());
            });
            dialog.show();
        });
    }

    private void enableDelOrderBtn(){
        delOrderBtn.setVisibility(View.VISIBLE);
        delOrderBtn.setOnClickListener(v -> {
            AlertDialog dialog = DialogUtil.getDialog(this, "删除订单", "确定要删除订单吗", (dialog1, which) -> {
                new Thread(() -> delOrder(info.order.getOrderId())).start();
                dialog1.dismiss();
                Toast.makeText(OrderInfoActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                finishActivity(info.order.getOrderId());
            });
            dialog.show();
        });
    }

    private void enableFinishOrderBtn(){
        finishOrderBtn.setVisibility(View.VISIBLE);
        finishOrderBtn.setOnClickListener(v -> {
            AlertDialog dialog = DialogUtil.getDialog(this, "关闭订单", "确定要关闭订单吗", (dialog1, which) -> {
                new Thread(() -> confirmOrder(info.order.getOrderId())).start();
                dialog1.dismiss();
                Toast.makeText(OrderInfoActivity.this, "关闭订单成功", Toast.LENGTH_SHORT).show();
                finishActivity(info.order.getOrderId());
            });
            dialog.show();
        });
    }

    public void finishActivity(int orderId){
        Intent intent = new Intent();
        intent.putExtra("orderId", orderId);
        setResult(RESULT_OK, intent);
        finish();
    }
}